package com.imooc.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 构建简单模式的生产者，发送消息
 */
public class FooProducer {
    public static void main(String[] args) throws IOException, TimeoutException {

        // 1. 创建连接工厂及相关参数 Factory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("imooc");
        connectionFactory.setPassword("imooc");

        // 2. 通过工厂创建连接 Connection
        Connection connection = connectionFactory.newConnection();

        // 3. 创建管道 Channel
        Channel channel = connection.createChannel();

        // 4. 定义队列 (简单模式，不需要交换机Exchange)

        /*
          (String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
          queue:队列名
          durable:是否持久化
          exclusive: 是否独占
          autoDelete: 是否自动删除
          arguments: map类型的其他参数
         */
        channel.queueDeclare("hello", true, false, false, null);

        // 5. 向队列发送消息
        /*
          (String exchange, String routingKey, AMQP.BasicProperties props, byte[] body)
          exchange: 交换机，简单模式没有，所以直接设置为 ""
          routingKey: 路由key，映射路径，如果交换机没有。则路由key和队列名保持一致
          props: 配置参数
          body: 消息数据
         */
        String msg = "hello world";
        channel.basicPublish("", "hello", null, msg.getBytes());

        // 6. 资源释放
        channel.close();
        connection.close();
    }
}
